<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use mbilling\BillingBundle\Model\UsersModel;
use mbilling\BillingBundle\Model\UsersTotalTransactionsModel;
use mbilling\BillingBundle\Model\UsersAdminLogsModel;
use mbilling\BillingBundle\Model\UsersTransactionsModel;
use mbilling\BillingBundle\Entity\users;
use mbilling\BillingBundle\Entity\usersTotalTransactions;
use mbilling\BillingBundle\Entity\usersAdminLogs;

use mbilling\BillingBundle\Form\UsersRegistrationForm;
use mbilling\BillingBundle\Form\UsersForm;
use mbilling\BillingBundle\Form\RestoreForm;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use mbilling\BillingBundle\Other\GeneratePassword;

class UsersController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        $users = $user_model->findAll();
        return $this->render('BillingBundle:Users:index.html.twig', array('users' => $users));
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        $totalTransaction_model = new UsersTotalTransactionsModel($em);
        
        $securityEncoderFactory = $this->get('security.encoder_factory');
        $userVariable = new users($securityEncoderFactory);
        //$user_model->create($user->initDefaultEntity());
        //return new RedirectResponse($this->generateUrl('users_show'));
        $form = $this->createForm(new UsersForm, $userVariable);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $user_model->create($form->getData());

                $acl = $this->get('acl');
                $acl->createPermissionsForAllAdmins($userVariable);
                if ($userVariable->isAdmin())
                {
                    $acl->createPermissionsForNewAdmin($userVariable);
                    $acl->createPermissionsForOne($userVariable, $userVariable, MaskBuilder::MASK_EDIT);
                }
                else
                    $acl->createPermissionsForOne($userVariable, $userVariable, MaskBuilder::MASK_OWNER);


                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $totalTransaction = new usersTotalTransactions();
                $totalTransaction->setMoney('0');
                $totalTransaction->setUserId($userVariable->getId());
                $totalTransaction_model->create($totalTransaction);

                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('4');//страница пользователи
                $log->setObjectId($userVariable->getId());//изменяемый объект
                $log->setActionTypeId('1');//создание пользователя
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('users_show'));
            }
        }
        return $this->render('BillingBundle:Users:create.html.twig', array('form' => $form->createView()));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        $userVariable = $user_model->findByPK($id);
        
        $acl = $this->get('acl');
        $acl->checkPermissions($userVariable, 'DELETE');
        $acl->removePermissionsForExAdmin($userVariable);
        $acl->removePermissionsForAllAdmins($userVariable);
        
        $user_model->removeByPK($id);
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();

        $log_model = new UsersAdminLogsModel($em);
        $log = new usersAdminLogs();
        $log->setAdminId($userCurrent->getId());
        $log->setPageId('4');//страница пользователи
        $log->setObjectId($id);//изменяемый объект
        $log->setActionTypeId('3');//удаление пользователя
        $log_model->create($log);
        return new RedirectResponse($this->generateUrl('users_show'));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        $userVariable = $user_model->findByPK($id);
        $userVariable->setPasswordConfirm($userVariable->getPassword());
        if ($userVariable->getPassword() != '')
            $temp_password = $userVariable->getPassword();

        $acl = $this->get('acl');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl->checkPermissions($userVariable, 'EDIT');
        
        $form = $this->createForm(new UsersForm, $userVariable);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                if ($userVariable->getPassword() == '')
                    $userVariable->setPassword($temp_password);
                if ($userCurrent->isAdmin() && !$this->get('session')->get('user'))//администратор
                {
                    $user_model->create($form->getData());
                }
                else
                {
                    $data = $form->getData();
                    $data->setStatusId('2');
                    $user_model->create($data);
                }
                if ($userVariable->isAdmin())//изменен статус на администратора
                {
                    $acl->createPermissionsForNewAdmin($userVariable);
                    $acl->createPermissionsForOne($userVariable, $userVariable, MaskBuilder::MASK_EDIT);
                }
                else
                {
                    $acl->removePermissionsForExAdmin($userVariable);
                }
                if ($userCurrent->isAdmin())
                {
                    if ($this->get('session')->get('user'))
                        return new RedirectResponse($this->generateUrl('orders_show'));
                    else
                        return new RedirectResponse($this->generateUrl('users_show'));
                }
                else
                    return new RedirectResponse($this->generateUrl('orders_show'));
            }
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Users:user_update.html.twig', array('form' => $form->createView()));
            else
                return $this->render('BillingBundle:Users:admin_update.html.twig', array('form' => $form->createView()));
        }
        else
            return $this->render('BillingBundle:Users:user_update.html.twig', array('form' => $form->createView()));
    }
    public function updatePersonAction()
    {
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $response = $this->forward('BillingBundle:Users:update', array('id'  => $this->get('session')->get('user')->getId()));
        else
            $response = $this->forward('BillingBundle:Users:update', array('id'  => $userCurrent->getId()));
        return $response;
    }
    public function registrationAction()
    {
        $em = $this->get('doctrine')->getEntityManager();
        $user_model = new UsersModel($em);
        $totalTransaction_model = new UsersTotalTransactionsModel($em);

        $securityEncoderFactory = $this->get('security.encoder_factory');
        $userVariable = new users($securityEncoderFactory);
        $form = $this->createForm(new UsersRegistrationForm, $userVariable);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            
            if ($form->isValid())
            {
                $data = $form->getData();
                $data->setStatusId('2');
                $user_model->create($data);

                $acl = $this->get('acl');
                if ($userVariable->getId() == '1')//не нашел другого способа выдать права первому пользователю-администратору
                {
                    $data->setStatusId('1');
                    $user_model->create($data);
                    $acl->createPermissionsForNewAdmin($userVariable);
                }
                else
                {
                    $acl->createPermissionsForOne($userVariable, $userVariable, MaskBuilder::MASK_OWNER);
                }
                $acl->createPermissionsForAllAdmins($userVariable);
                if ($userVariable->isAdmin())
                    $acl->createPermissionsForOne($userVariable, $userVariable, MaskBuilder::MASK_EDIT);

                $totalTransaction = new usersTotalTransactions();
                $totalTransaction->setMoney('0');
                $totalTransaction->setUserId($userVariable->getId());
                $totalTransaction_model->create($totalTransaction);
                return new RedirectResponse($this->generateUrl('login'));
            }
        }
        return $this->render('BillingBundle:Users:registration.html.twig', array('form' => $form->createView()));
    }
    public function getMailAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        $userVariable = new users();
        $userVariable->setPassword('123');
        $form = $this->createForm(new RestoreForm, $userVariable);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                if (!$user_model->checkByLogin($form->get('login')->getData()))
                    return $this->render('BillingBundle:Users:restore.html.twig', array('form' => $form->createView(), 'message' => 'пользователь не найден!'));
                $userVariable = $user_model->findByLogin($form->get('login')->getData());
                $restorePassword = new GeneratePassword();
                $mailer = $this->get('mailer');

                $message = \Swift_Message::newInstance()
                    ->setSubject('Восстановление пароля. 1 этап')
                    ->setFrom('do.not.reply@docker.ru')
                    ->setTo($userVariable->getLogin())
                    ->setBody($this->renderView('BillingBundle:Users:restore_mail.html.twig', array('user' => $userVariable,
                                                                                                    'link' => $restorePassword->createLoginAsPartnerLink($userVariable->getId(), $userVariable->getLogin(), $userVariable->getPassword()))), 'text/html');
                $mailer->send($message);
                
                return new RedirectResponse($this->generateUrl('login'));
            }
        }
        return $this->render('BillingBundle:Users:restore.html.twig', array('form' => $form->createView(), 'message' => ''));
    }
    public function restoreAction($sHash)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $restorePassword = new GeneratePassword();
        $user_model = new UsersModel($em);
        $userVariable = $user_model->findByHash($sHash, $restorePassword->getLoginAsParentSalt());
        $id = $userVariable->getId();
        if (isset($id))
        {
            $userVariable->setPassword($restorePassword->generatePassword(8, 2));
            $user_model->create($userVariable);

            $mailer = $this->get('mailer');
            $message = \Swift_Message::newInstance()
                ->setSubject('Восстановление пароля. 2 этап')
                ->setFrom('do.not.reply@docker.ru')
                ->setTo($userVariable->getLogin())
                ->setBody($this->renderView('BillingBundle:Users:new_password_mail.html.twig', array('user' => $userVariable)), 'text/html');
            $mailer->send($message);
        }
        return new RedirectResponse($this->generateUrl('login'));
    }
    public function renderInfoAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent == 'anon.')
        {
            return new Response('');
        }
        $totalTransaction_model = new UsersTotalTransactionsModel($em);
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
        {
            $totalTransaction = $totalTransaction_model->findByUserId($this->get('session')->get('user')->getId());
            return $this->render('BillingBundle:Users:info.html.twig', array('real_user' => '0', 'user' => $this->get('session')->get('user'), 'totalTransaction' => $totalTransaction));
        }
        $totalTransaction = $totalTransaction_model->findByUserId($userCurrent->getId());
        
        $summ = 0;
        $transaction_model = new UsersTransactionsModel($em);
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $transactions = $transaction_model->findByUserId($this->get('session')->get('user')->getId());
        else
            $transactions = $transaction_model->findByUserId($userCurrent->getId());
        foreach($transactions as $transaction)
        {
            if ($transaction->getIsRegular())
            {
                if ($transaction->getIsAdding())
                {
                    $summ -= $transaction->getMoney();
                }
                else
                {
                    $summ += $transaction->getMoney();
                }
            }
        }
        return $this->render('BillingBundle:Users:info.html.twig', array('real_user' => '1', 'user' => $userCurrent, 'totalTransaction' => $totalTransaction, 'summ' => $summ));
    }
    public function emulationAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        $userVariable = $user_model->findByPK($id);
        $this->get('session')->set('user', $userVariable);
        return new RedirectResponse($this->generateUrl('orders_show'));
    }
    public function renderAdminLinkAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent == 'anon.')
        {
            return new Response('');
        }
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            return $this->render('BillingBundle:Users:admin_link.html.twig', array());
        else
            return new Response('');
    }
    public function logoutAction()
    {
        $this->get('session')->set('user', NULL);
        return new RedirectResponse($this->generateUrl('users_show'));
    }
}